
Security News
Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
koa-session
Advanced tools
koa-session is a session middleware for Koa, a popular web framework for Node.js. It provides a way to manage user sessions, including storing session data, setting session cookies, and handling session expiration.
Basic Session Setup
This code sets up a basic Koa application with session management. It configures the session middleware with various options like cookie key, max age, and httpOnly flag. The middleware is then used to track the number of views for each session.
const Koa = require('koa');
const session = require('koa-session');
const app = new Koa();
app.keys = ['some secret hurr'];
const CONFIG = {
key: 'koa:sess', // cookie key (default is koa:sess)
maxAge: 86400000, // cookie's max age in ms (1 day)
autoCommit: true, // automatically commit headers (default true)
overwrite: true, // can overwrite or not (default true)
httpOnly: true, // httpOnly or not (default true)
signed: true, // signed or not (default true)
rolling: false, // Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown.
renew: false, // renew session when session is nearly expired, so we can always keep user logged in.
};
app.use(session(CONFIG, app));
app.use(ctx => {
if (ctx.path === '/favicon.ico') return;
let n = ctx.session.views || 0;
ctx.session.views = ++n;
ctx.body = n + ' views';
});
app.listen(3000);
Custom Session Store
This code demonstrates how to use a custom session store with koa-session. The custom store is implemented using a simple in-memory Map. The store object provides methods for getting, setting, and destroying session data.
const Koa = require('koa');
const session = require('koa-session');
const app = new Koa();
app.keys = ['some secret hurr'];
const store = {
storage: new Map(),
get(key) {
return this.storage.get(key);
},
set(key, sess) {
this.storage.set(key, sess);
},
destroy(key) {
this.storage.delete(key);
}
};
const CONFIG = {
store,
};
app.use(session(CONFIG, app));
app.use(ctx => {
if (ctx.path === '/favicon.ico') return;
let n = ctx.session.views || 0;
ctx.session.views = ++n;
ctx.body = n + ' views';
});
app.listen(3000);
Session Regeneration
This code shows how to regenerate a session in koa-session. When the user accesses the '/regenerate' path, the session is regenerated, which can be useful for security purposes, such as after a user logs in.
const Koa = require('koa');
const session = require('koa-session');
const app = new Koa();
app.keys = ['some secret hurr'];
const CONFIG = {};
app.use(session(CONFIG, app));
app.use(async ctx => {
if (ctx.path === '/favicon.ico') return;
if (ctx.path === '/regenerate') {
await ctx.regenerateSession();
ctx.body = 'Session regenerated';
} else {
let n = ctx.session.views || 0;
ctx.session.views = ++n;
ctx.body = n + ' views';
}
});
app.listen(3000);
express-session is a session middleware for Express, another popular web framework for Node.js. It provides similar functionalities to koa-session, such as session storage, cookie management, and session expiration. However, it is designed to work with Express rather than Koa.
cookie-session is a lightweight session middleware that stores session data in cookies rather than on the server. This can be useful for small session data and simplifies the setup by not requiring a session store. It works with both Koa and Express.
koa-generic-session is another session middleware for Koa. It provides more flexibility and customization options compared to koa-session, such as support for different session stores and more advanced session management features.
Simple session middleware for Koa. Defaults to cookie-based sessions and supports external stores.
Requires Node 8.0.0 or greater for async/await support
$ npm install koa-session
6.x changed the default cookie key from koa:sess
to koa.sess
to ensure set-cookie
value valid with HTTP spec.see issue. If you want to be compatible with the previous version, you can manually set config.key
to koa:sess
.
View counter example:
const session = require('koa-session');
const Koa = require('koa');
const app = new Koa();
app.keys = ['some secret hurr'];
const CONFIG = {
key: 'koa.sess', /** (string) cookie key (default is koa.sess) */
/** (number || 'session') maxAge in ms (default is 1 days) */
/** 'session' will result in a cookie that expires when session/browser is closed */
/** Warning: If a session cookie is stolen, this cookie will never expire */
maxAge: 86400000,
autoCommit: true, /** (boolean) automatically commit headers (default true) */
overwrite: true, /** (boolean) can overwrite or not (default true) */
httpOnly: true, /** (boolean) httpOnly or not (default true) */
signed: true, /** (boolean) signed or not (default true) */
rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
secure: true, /** (boolean) secure cookie*/
sameSite: null, /** (string) session cookie sameSite options (default null, don't set it) */
};
app.use(session(CONFIG, app));
// or if you prefer all default config, just use => app.use(session(app));
app.use(ctx => {
// ignore favicon
if (ctx.path === '/favicon.ico') return;
let n = ctx.session.views || 0;
ctx.session.views = ++n;
ctx.body = n + ' views';
});
app.listen(3000);
console.log('listening on port 3000');
The cookie name is controlled by the key
option, which defaults
to "koa.sess". All other options are passed to ctx.cookies.get()
and
ctx.cookies.set()
allowing you to control security, domain, path,
and signing among other settings.
encode/decode
SupportUse options.encode
and options.decode
to customize your own encode/decode methods.
valid()
: valid session value before use itbeforeSave()
: hook before save sessionThe session is stored in a cookie by default, but it has some disadvantages:
You can store the session content in external stores (Redis, MongoDB or other DBs) by passing options.store
with three methods (these need to be async functions):
get(key, maxAge, { rolling, ctx })
: get session object by keyset(key, sess, maxAge, { rolling, changed, ctx })
: set session object for key, with a maxAge
(in ms)destroy(key, {ctx})
: destroy session for keyOnce you pass options.store
, session storage is dependent on your external store -- you can't access the session if your external store is down. Use external session stores only if necessary, avoid using session as a cache, keep the session lean, and store it in a cookie if possible!
The way of generating external session id is controlled by the options.genid(ctx)
, which defaults to uuid.v4()
.
If you want to add prefix for all external session id, you can use options.prefix
, it will not work if options.genid(ctx)
present.
If your session store requires data or utilities from context, opts.ContextStore
is also supported. ContextStore
must be a class which claims three instance methods demonstrated above. new ContextStore(ctx)
will be executed on every request.
koa-session
will emit event on app
when session expired or invalid:
session:missed
: can't get session value from external store.session:invalid
: session value is invalid.session:expired
: session value is expired.External key is used the cookie by default, but you can use options.externalKey
to customize your own external key methods. options.externalKey
with two methods:
get(ctx)
: get the external keyset(ctx, value)
: set the external keyReturns true if the session is new.
if (this.session.isNew) {
// user has not logged in
} else {
// user has already logged in
}
Get cookie's maxAge.
Set cookie's maxAge.
Get session external key, only exist when external session store present.
Save this session no matter whether it is populated.
Session headers are auto committed by default. Use this if autoCommit
is set to false
.
To destroy a session simply set it to null
:
this.session = null;
MIT
7.0.0 (2025-01-19)
features
4cd3bef
] - feat: Add Session.regenerate() method (#221) (Jürg Lehni <juerg@scratchdisk.com>)fixes
e2de39e
] - fix: keep crc v3 (#223) (fengmk2 <fengmk2@gmail.com>)features
878669e
] - feat: update uuid to v8 (#218) (zhennann <zhen.nann@icloud.com>)others
df2d28f
] - test: run ci on GitHub Action (#222) (fengmk2 <fengmk2@gmail.com>)features
7cde341
] - feat: add session.externalKey (#207) (Yiyu He <dead_horse@qq.com>)features
32e3526
] - feat: add context to external store .get() and .set() options params (#201) (Ngorror <ngorror@gmail.com>)others
f765595
] - chore: Create LICENSE File (#195) (Dominic Egginton <dominic.egginton@gmail.com>)
6.0.0 / 2020-04-26
==================fixes
d34fc8e
] - fix: RFC6265 compliant default cookie name (#197) (zacanger <zac@zacanger.com>)
koa.sess
rather than koa:sess
fixes
ecd1f5e
] - fix: don't set any value to sameSite by default (#194) (fengmk2 <fengmk2@gmail.com>)features
cb09a09
] - feat: support session cookie sameSite options (#193) (fengmk2 <fengmk2@gmail.com>)fixes
909d93f
] - fix: correctly expire cookies for nullified sessions (Justin <jmitchell38488@users.noreply.github.com>)fixes
c23bab4
] - fix: remvoe unused code (dead-horse <dead_horse@qq.com>)fixes
77968e3
] - fix: ensure ctx.session always has value (dead-horse <dead_horse@qq.com>)features
39ca830
] - feat: add the parameter "ctx" to the function "genid" so can get the … (#173) (松松 <1733458402@qq.com>)others
3d57a44
] - docs: add genid(ctx) in readme (dead-horse <dead_horse@qq.com>)features
b79134d
] - feat: make sure session id is global unique (#170) (fengmk2 <fengmk2@gmail.com>)fixes
c2b4259
] - fix: remove package-lock.json (fengmk2 <fengmk2@gmail.com>)others
23ad871
] - deps: Fix security vulnerabilities from npm audit (#163) (Douglas Wade <douglas.b.wade@gmail.com>)1600aab
] - test: changed "ctx.session is mockable" tests names to more appropriate (#158) (Vitaliy Zaytsev <teh.kroleg@gmail.com>)features
5f12f70
] - feat: allow init multi session middleware (#159) (killa <killa123@126.com>)fixes
89c048a
] - fix: moved "pedding" package to dev dependencies (#155) (Vitaliy Zaytsev <teh.kroleg@gmail.com>)features
81906f7
] - feat: support options.externalKey #88 (#149) (Tree Xie <vicansocanbico@gmail.com>)features
7241400
] - feat: Add autoCommit option (#139) (Jonas Galvez <jonasgalvez@gmail.com>)fixes
6f1a41c
] - fix: session not works (#136) (吖猩 <whxaxes@qq.com>)others
95272ff
] - fix typo in README.md (#134) (Maples7 <maples7@163.com>)fixes
c487944
] - fix: Fixes a bug that reset the cookie expire date to the default (1 day) when using browser sessions (maxAge: 'session') (#117) (Adriano <adrianocola@gmail.com>)others
9050605
] - deps: Upgrade debug@^3.1.0 (#107) (Daniel Tseng <s92f002@hotmail.com>)c48e1e0
] - Update Readme.md (#123) (Wellington Soares <well.cco@gmail.com>)fixes
bdb4fd4
] - fix: ensure store expired after cookie (dead-horse <dead_horse@qq.com>)features
bb5f4bf
] - feat: support opts.renew (#111) (Yiyu He <dead_horse@qq.com>)fixes
72fa5fe
] - fix: emit event in next tick (dead-horse <dead_horse@qq.com>)features
a2401c8
] - feat: emit event expose ctx (dead-horse <dead_horse@qq.com>)features
f00c1ef
] - feat: emit events when session invalid (#108) (Yiyu He <dead_horse@qq.com>)others
b976b10
] - perf: no need to assign opts (#103) (Yiyu He <dead_horse@qq.com>)c040b59
] - chore: fix example bug and use syntactic sugar (#97) (Runrioter Wung <runrioter@gmail.com>)906277a
] - docs: copyediting (#85) (Nate Silva <natesilva@users.noreply.github.com>)features
ec88cfb
] - feat: support options.prefix for external store (#93) (Yiyu He <dead_horse@qq.com>)session.save()
, won't set cookie immediately now.session.changed()
..save()
.save()
FAQs
Koa cookie session middleware with external store support
We found that koa-session demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 8 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Security News
React's CRA deprecation announcement sparked community criticism over framework recommendations, leading to quick updates acknowledging build tools like Vite as valid alternatives.
Security News
Ransomware payment rates hit an all-time low in 2024 as law enforcement crackdowns, stronger defenses, and shifting policies make attacks riskier and less profitable.